<template>
  <div>
    <Header :left="true" leftText="返回" title="设备报修" />
    <Row style="margin-top: 80px">
      <div class="container dwo">
        <div class="card_under">
          <NoticeBar color="#1989fa" background="#ecf9ff" left-icon="video"
            >多媒体信息</NoticeBar
          >
          <Field
            v-model="equipRepairVo.remark"
            size="large"
            rows="1"
            autosize
            label="报修描述"
            type="textarea"
            maxlength="50"
            placeholder="请输入报修描述"
            show-word-limit
          />
          <Field
            :readonly="true"
            size="large"
            name="checkres"
            @click="showCamera"
            label="点击拍照上传"
            placeholder="————点击拍照————"
            right-icon="assets/right.png"
          />
          <div
            v-if="
              equipRepairVo.picList !== undefined &&
              equipRepairVo.picList.length > 0
            "
          >
            <div
              class="van-uploader"
              v-for="(imgUrl, ks) in equipRepairVo.picList"
              :key="ks"
            >
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div
                    @click="picShow(ks)"
                    class="van-image van-uploader__preview-image"
                  >
                    <img :src="imgUrl" class="van-image__img" />
                  </div>
                  <div
                    class="van-uploader__preview-delete"
                    @click="delObj('pic', imgUrl)"
                  >
                    <i
                      class="van-icon van-icon-cross van-uploader__preview-delete-icon"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <Field name="checkres" label="视频拍摄" size="large">
            <template #input>
              <Button
                class="mg5"
                icon="play-circle"
                plain
                round
                hairline
                size="small"
                type="primary"
                @click="startVideoRecord"
                >录制</Button
              >
            </template>
          </Field>
          <div
            v-if="
              equipRepairVo.videoList !== undefined &&
              equipRepairVo.videoList.length > 0
            "
          >
            <div
              class="van-uploader"
              v-for="(videoUrl, index) in equipRepairVo.videoList"
              :key="index"
            >
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="showVideo(videoUrl)" class="tag_margin">
                    <Tag plain size="large" type="danger"
                      >视频文件{{ index + 1 }}</Tag
                    >
                  </div>
                  <div
                    class="van-uploader__preview-delete"
                    @click="delObj('video', videoUrl)"
                  >
                    <i
                      class="van-icon van-icon-cross van-uploader__preview-delete-icon"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <Field name="checkres" label="录制语音" size="large">
            <template #input>
              <Button
                class="mg5"
                plain
                round
                hairline
                icon="volume"
                size="small"
                type="warning"
                :loading="btnLoading"
                loading-text="正在播放"
                @touchstart.native="recordAudio"
                @touchend.native="stopRecordAudio"
                >按住说话</Button
              >
            </template>
          </Field>
          <div
            v-if="
              equipRepairVo.audioList !== undefined &&
              equipRepairVo.audioList.length > 0
            "
          >
            <div
              class="van-uploader"
              v-for="(audioUrl, adIndex) in equipRepairVo.audioList"
              :key="adIndex"
            >
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="showAudio(audioUrl)" class="tag_margin">
                    <Tag plain size="large" type="success"
                      >语音文件{{ adIndex + 1 }}</Tag
                    >
                  </div>
                  <div
                    class="van-uploader__preview-delete"
                    @click="delObj('audio', audioUrl)"
                  >
                    <i
                      class="van-icon van-icon-cross van-uploader__preview-delete-icon"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <NoticeBar
            color="#1989fa"
            background="#ecf9ff"
            left-icon="description"
            >文本信息</NoticeBar
          >
          <Field
            readonly
            label="设备编码"
            size="large"
            right-icon="scan"
            @click="showScanner"
            v-model="equipRepairVo.equipCode"
          >
            ></Field
          >
          <Field
            readonly
            label="设备名称"
            size="large"
            v-model="equipRepairVo.equipName"
          />
          <Field
            readonly
            label="报修用户"
            size="large"
            v-model="user.nickName"
          />
          <Field
            readonly
            label="报修时间"
            size="large"
            v-model="equipRepairVo.requestTime"
          />
          <Row style="margin: 5px 10px 0 10px" gutter="16">
            <Col span="12">
              <Button block class="buttonleft" @click="concel" color="#f58220"
                >取消</Button
              >
            </Col>
            <Col span="12">
              <Button block class="buttonright" color="#138087" @click="doCheck"
                >提交信息</Button
              >
            </Col>
          </Row>
        </div>
      </div>
    </Row>

    <!-- 报修单弹出层 -->
    <van-popup
      v-model="requestDialog"
      position="top"
      :style="{ height: '100%' }"
    >
      <van-row style="margin-top: 35px">
        <van-divider
          :style="{
            color: '#1989fa',
            borderColor: '#1989fa',
            padding: '0 16px',
          }"
        >
          当前设备未完成维修的报修单
        </van-divider>
      </van-row>

      <van-button
        :block="true"
        plain
        class="concelReport"
        type="primary"
        @click="concelReport"
        text="取消报修"
      />
      <van-button
        :block="true"
        class="confirmReport"
        type="warning"
        @click="requestDialog = false"
        text="继续报修"
      />
      <div class="textScroll">
        <!-- 循环数据开始 -->
        <div v-for="item in requestList" :key="item.id">
          <div style="width: 100%; background-color: #f3f4f8; height: 5px">
            <span></span>
          </div>
          <div class="divStyle" @click.prevent="showDetail(item)">
            <van-row style="margin-top: 10px; margin-left: 10px">
              <van-col span="18" style="color: #a9a9a9">
                <van-icon name="assets/time.png" />报修时间:
                {{ item.requestTime }}
              </van-col>
              <van-col span="3">
                <van-button
                  style="width: 105px; height: 30px; right: 0px"
                  @click="showMedia(item.id)"
                  type="primary"
                  text="多媒体查看"
                />
              </van-col>
            </van-row>
            <van-divider />

            <van-row style="margin-left: 10px">
              <van-col span="18" style="color: #a9a9a9"
                >报修单号：{{ item.requestCode }}</van-col
              >
            </van-row>
            <van-row style="margin-left: 10px; margin-top: 10px">
              <van-col span="18" style="color: #a9a9a9"
                >当前状态：{{ item.status }}</van-col
              >
            </van-row>
            <van-row style="margin-left: 10px; margin-top: 10px">
              <van-col span="18" style="color: #a9a9a9"
                >报修说明：{{ item.remark }}</van-col
              >
            </van-row>
            <van-row
              v-if="item.lastPromptTime != null"
              style="margin-left: 10px; margin-top: 10px"
            >
              <van-col span="18" style="color: #a9a9a9"
                >最近催促时间：{{ item.lastPromptTime }}</van-col
              >
            </van-row>

            <van-row
              v-if="item.promptTimes != null"
              style="margin-left: 10px; margin-top: 10px"
            >
              <van-col span="18" style="color: #a9a9a9"
                >累计催促次数：{{ item.promptTimes }}</van-col
              >
            </van-row>

            <van-row style="margin-left: 10px; margin-top: 10px">
              <van-col span="18" style="color: #a9a9a9"
                >报修人：{{ item.requestUser }}</van-col
              >

              <van-col span="3">
                <van-button
                  color="#f58220"
                  style="
                    width: 75px;
                    height: 30px;
                    margin-bottom: 10px;
                    right: 0px;
                  "
                  type="primary"
                  @click="prompt(item.id)"
                  text="催促"
                />
              </van-col>
              <!-- <van-col span="3"><van-image width="40" height="30" src="assets/noAssign.png"/></van-col> -->
            </van-row>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 报修多媒体弹窗 -->
    <van-popup
      v-model="detailShow"
      round
      position="bottom"
      :style="{ height: '60%' }"
    >
      <div>
        <van-row>
          <van-col>
            <van-image
              width="40"
              height="30"
              style="margin-left: 5px; margin-top: 5px"
              src="assets/block.png"
            />
          </van-col>
          <van-col style="margin-top: 8px">多媒体信息</van-col>
        </van-row>
      </div>
      <!-- 多媒体信息 -->
      <div class="divMedia">
        <van-row style="margin-top: 10px">
          <van-col
            span="4"
            style="
              font-weight: bold;
              color: #a9a9a9;
              margin-left: 10px;
              margin-top: 8px;
            "
            >视频：</van-col
          >
          <van-col span="14" style="color: #a9a9a9">
            <!-- 循环显示视频 -->
            <div
              v-show="vedioShow"
              v-for="item in vedioList"
              :key="item.id"
              style="margin-left: -10px"
            >
              <van-image
                style="float: left"
                width="50"
                height="40"
                @click="showVideo(item.filePath)"
                src="assets/vedio.png"
              />
            </div>
          </van-col>
        </van-row>
        <van-divider style="margin-top: 0px" />
        <van-row style="margin-top: 10px">
          <van-col
            span="4"
            style="
              font-weight: bold;
              color: #a9a9a9;
              margin-left: 10px;
              margin-top: 8px;
            "
            >照片:</van-col
          >
          <van-col span="14" style="color: #a9a9a9">
            <van-uploader
              v-show="photoShow"
              v-model="photoList"
              :deletable="false"
              multiple
              :max-count="pictureNum"
            />
          </van-col>
        </van-row>
        <van-divider style="margin-top: 0px" />
        <van-row style="margin-top: 10px">
          <van-col
            span="4"
            style="
              font-weight: bold;
              color: #a9a9a9;
              margin-left: 10px;
              margin-top: 8px;
            "
            >语音：</van-col
          >
          <van-col span="14" style="color: #a9a9a9">
            <div
              v-show="audioShow"
              @click="playArm"
              style="
                background-color: #00ff33;
                width: 140px;
                height: 35px;
                margin-left: -10px;
              "
            >
              <van-image
                v-show="audioStop"
                width="40"
                height="30"
                style="margin-right: 3px; float: left"
                src="assets/voice.png"
              >
              </van-image>
              <van-loading
                v-show="audioLoad"
                style="float: center"
                color="white"
                ><span style="color: white; font-size: 15px"
                  >播放中...</span
                ></van-loading
              >
            </div>
          </van-col>
        </van-row>
      </div>
    </van-popup>
  </div>
</template>
<script>
import {
  Icon,
  NoticeBar,
  Button,
  Row,
  Tag,
  ImagePreview,
  Toast,
  Divider,
  Image as VanImage,
  Field,
  CellGroup,
  Cell,
  Popup,
  Picker,
  Uploader,
  Col,
  Dialog,
} from "vant";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";
import { _httpClient } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
Vue.use(ImagePreview);
Vue.use(Popup);
Vue.use(Icon);
Vue.use(Button);
Vue.use(Col);
Vue.use(Row);
Vue.use(Uploader);
Vue.use(Divider);
export default {
  name: "equip_fix_info",
  components: {
    Button,
    NoticeBar,
    Header,
    ImagePreview,
    Icon,
    Row,
    Tag,
    VanImage,
    Toast,
    Divider,
    Field,
    CellGroup,
    Cell,
    Uploader,
    Popup,
    Picker,
    Col,
    Dialog,
  },
  data() {
    return {
      requestDialog: false,
      detailShow: false,
      requestList: [],
      btnLoading: false,
      commitLoading: false,
      //多媒体文件
      photoList: [
        //图片
      ],
      pictureNum: 0, //照片数量
      playing: "播放中...", //语音播放中字幕
      audioLoad: false, // 语音播放中
      audioStop: true, // 语音暂停
      photoShow: false, //照片显示控制
      vedioShow: false, //视频显示控制
      audioShow: false, //语音显示控制
      vedioList: [], //视频
      audioPath: "", //语音
      progress: 0,
      operationType: 0,
      user: {
        classes: "",
        nickName: "",
        depart: "",
      },
      equipRepairVo: {
        eqKey: null,
        picList: [],
        videoList: [],
        audioList: [],
        requestTime: this.getNowTime(),
        requestUser: "",
      },
      uploadSuccess: false,
    };
  },
  created() {
    this.user = JSON.parse(storage.get("user"));
    this.equipRepairVo = {
      equipCode: this.$ac.pageParam.equipCode,
      equipName: this.$ac.pageParam.equipName,
      eqKey: this.$ac.pageParam.eqKey,
      requestTime: this.getNowTime(),
      remark: null,
      picList: [],
      videoList: [],
      audioList: [],
    };
    this.operationType = this.$ac.pageParam.operationType;
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) {}
    );

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}
    this.queryNoFinishedRequest(this.$ac.pageParam.eqKey);
  },
  mounted() {
    //退出提示
    var ci = 0;
    var time1, time2;
    let that = this;
    that.$ac.addEventListener(
      {
        name: "keyback",
      },
      function (ret, err) {
        if (ci == 0) {
          time1 = new Date().getTime();
          ci = 1;
          api.toast({
            msg: "再按一次返回键离开当前页面",
          });
        } else if (ci == 1) {
          time2 = new Date().getTime();
          if (time2 - time1 < 3000) {
            that.$ac.confirm(
              {
                title: "离开页面提示",
                msg: "表单数据未保存，直接离开会丢失，请确认是否保存？",
                buttons: ["确定", "坚决离开", "我再想想"],
              },
              function (ret, err) {
                if (ret.buttonIndex == 1) {
                  //保存数据
                  that.doCheck();
                } else if (ret.buttonIndex == 2) {
                  api.sendEvent({
                    name: "result",
                    extra: {
                      res: "next",
                    },
                  });
                  that.$ac.closeWin();
                } else {
                  // if you have a dream, why not give up?
                }
              }
            );
          } else {
            ci = 0;
            api.toast({
              msg: "再按一次返回键离开当前页面",
            });
          }
        }
      }
    );
  },
  methods: {
    //打开扫描
    showScanner() {
      let _this = this;
      _this.itemsOne = [];
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {
        var zyHmsScan = api.require("zyHmsScan");
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          _this.equipRepairVo.equipCode = ret.result;
          //api.alert({ msg: JSON.stringify(ret) });
        });
        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 15, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //         let res = ret.result.split(",");
        //         _this.equipRepairVo.equipCode = ret.result;
        //     }
        //   }
        // );
        //    QRScan.closeCustomizedScanner();
      } else {
        var FNScanner = _this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                let res = ret.content.split(",");
                _this.equipRepairVo.equipCode = ret.content;
              }
            } else {
              alert(JSON.stringify(err));
            }
          }
        );
      }
    },

    async queryNoFinishedRequest(equipKey) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      let that = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
            "/app/repair/requestInfo/noFinishedRequest",
          {
            body: { eqKey: equipKey },
          }
        );
        Toast.clear();
        if (res.code === 200) {
          this.requestDialog = true;
          this.requestList = res.data;
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //取消报修
    concelReport() {
      api.closeWin();
    },

    //查询维修单多媒体信息
    async showMedia(requestId) {
      let _this = this;
      _this.detailShow = true;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/app/repair/requestFile/selectFiles",
          {
            body: { requestId: requestId },
          }
        );

        if (res.code === 200) {
          Toast.clear();
          if (res.rows.length > 0) {
            //筛选图片、视频、录音
            let pictures = [];
            let vedios = [];
            let audios = [];
            _this.vedioList = [];
            _this.pictures = [];
            _this.audioPath = null;
            for (let i = 0; i < res.rows.length; i++) {
              if (res.rows[i].fileType == "0") {
                //照片
                let paths = res.rows[i].filePath.split(";");
                for (let j = 0; j < paths.length; j++) {
                  let num = 0;
                  if (paths[j] != "") {
                    let picture = { url: paths[j] };
                    pictures.push(picture);
                    num++;
                  }
                  _this.pictureNum = num;
                }
                //显示照片
                _this.photoShow = true;
              } else if (res.rows[i].fileType == "1") {
                let paths = res.rows[i].filePath.split(";");
                for (let j = 0; j < paths.length; j++) {
                  if (paths[j] != "") {
                    let vedio = { filePath: paths[j] };
                    _this.vedioList.push(vedio);
                  }
                }
                //视频
                // _this.vedioList.push(res.rows[i])
                _this.vedioShow = true;
              } else if (res.rows[i].fileType == "2") {
                //语音
                let paths = res.rows[i].filePath.split(";");
                for (let j = 0; j < paths.length; j++) {
                  if (paths[j] != "") {
                    _this.audioPath = paths[j];
                    _this.audioShow = true;
                    break;
                  }
                }
              }
            }
            _this.photoList = pictures; //照片数组赋值
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.clear();
        alert(JSON.stringify(e));
      }
    },
    //催促报修
    async prompt(requestId) {
      let _this = this;
      if (requestId != null) {
        Toast.loading({
          mask: true,
          forbidClick: true,
          duration: 0,
          message: "请稍等...",
        });
        let that = this;
        try {
          let res = await _httpClient.post(
            _httpClient.getApiPrefix() +
              "/app/repair/requestInfo/promptRequest",
            {
              body: { id: requestId },
            }
          );
          Toast.clear();
          if (res.code === 200) {
            Dialog.alert({
              message: "催促成功",
              theme: "round-button",
            }).then(() => {
              // on close
            });
            _this.queryNoFinishedRequest(_this.equipRepairVo.eqKey);
          } else {
            Dialog.alert({
              message: res.msg,
              theme: "round-button",
            }).then(() => {
              // on close
            });
          }
        } catch (e) {
          Toast.fail(JSON.stringify(e));
        }
      }
    },

    //语音播放
    playArm() {
      //判断是播放还是暂停
      if (!this.audioLoad) {
        this.audioLoad = true;
        this.audioStop = false;
        if (this.audioPath == "") {
          Dialog.alert({
            message: "当前无语音信息",
            theme: "round-button",
          }).then(() => {
            // on close
          });
        }
        var audioStreamer = api.require("audioStreamer");
        let _this = this;
        audioStreamer.addEventListener({}, function (ret) {
          if (ret.state == "finished") {
            _this.audioLoad = false;
            _this.audioStop = true;
          }
        });
        if (api.systemType == "ios") {
          api.download(
            {
              url: _this.audioPath,
            },
            function (res) {
              if (res.state == 1) {
                api.startPlay(
                  {
                    path: res.savePath,
                  },
                  function (ret, err) {
                    if (ret) {
                      // _that.activeAudio = ''
                    } else {
                      alert(JSON.stringify(err));
                    }
                  }
                );
              }
            }
          );
        } else {
          audioStreamer.openPlayer(
            {
              path: _this.audioPath,
            },
            function (ret) {}
          );
        }
      } else {
        var audioStreamer = api.require("audioStreamer");
        audioStreamer.pause();
        this.audioLoad = false;
        this.audioStop = true;
      }
    },

    picShow(pIndex) {
      ImagePreview({
        images: this.equipRepairVo.picList || [],
        showIndicators: true,
        startPosition: pIndex || 0,
        showIndex: false,
      });
    },
    showCamera() {
      let that = this;
      //alert("手机系统"+api.deviceName.toLowerCase());
      //判断设备系统类型
      if (api.systemType == "ios") {
        that.iosCamera();
      } else {
        if (api.deviceName.toLowerCase() == "vivo") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "oppo") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "oneplus") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "honor") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "xiaomi") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "meizu") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "realme") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "huawei") {
          that.vivoCamera();
          // that.otherCamera();
          // that.otherCameraPlus();
        } else if (api.deviceName.toLowerCase() == "ptac") {
          that.vivoCamera();
        } else {
          that.vivoCamera();
          // that.otherCameraPlus();
          // that.otherCamera();
        }
        // var phoneInfo = api.require('phoneInfo')
        // phoneInfo.getBaseInfo(function(ret, err) {
        //   if (ret.status) {
        //     if (ret.brand == 'vivo') {
        //       // that.vivoCamera()
        //       that.iosCamera()
        //     } else if (ret.brand == 'oppo') {
        //       that.oppoReno2Camera()
        //     } else {
        //       that.otherCamera()
        //     }
        //   } else {
        //     api.alert({ msg: err.msg })
        //   }
        // })
      }
    },

    vivoCamera() {
      let that = this;
      var FNPhotograph = api.require("FNPhotograph");
      FNPhotograph.open(
        {
          album: false,
          quality: "high",
          isShowAlbum: false,
          // useAdvanceFeature: true,
          // pictureSize: '2075x1080',
          // previewSize: '2075x1080',
        },
        function (ret) {
          if (ret && ret.eventType == "takePhoto") {
            let imgSrc = ret.imagePath;
            if (imgSrc && imgSrc != "") {
              FNPhotograph.close();
              that.imageFilter(imgSrc);
            }
          }
        }
      );
    },

    oppoReno2Camera() {
      let _this = this;
      api.getPicture(
        {
          sourceType: "camera",
          encodingType: "jpg",
          mediaValue: "pic",
          allowEdit: false,
          destinationType: "url",
          quality: 50,
        },
        function (ret, err) {
          // 获取拍照数据并处理
          if (ret) {
            let imgSrc = ret.data;
            if (imgSrc && imgSrc != "") {
              _this.imageFilter(imgSrc);
            }
          }
        }
      );
    },
    xiaomiCamera() {
      let that = this;
      var cameraTool = api.require("cameraTool");
      cameraTool.openCamera(function (ret, err) {
        let imgPath = ret.imgPath;
        if (imgPath && imgPath != "") {
          that.imageFilter(imgPath);
        }
      });
    },
    otherCamera() {
      let that = this;
      // var cameraTool = api.require('cameraTool')
      // cameraTool.openCamera(function(ret, err) {
      //   let imgPath = ret.imgPath
      //   if (imgPath && imgPath != '') {
      //     that.imageFilter(imgPath)
      //   }
      // })
      var module = api.require("easyCamera");
      var param = {
        typeString: "image", // 或者'video-20'
      };
      var resultCallback = function (ret, err) {
        var msg = ret.msg;
        if (msg && msg != "") {
          that.imageFilter(msg);
        }
      };
      module.openCamera(param, resultCallback);
    },
    otherCameraPlus() {
      let that = this;
      var ox = api.require("oxWxRecorder");
      ox.getPermission(function (ret) {
        var code = ret.code;
        if (code == 1) {
          ox.open(
            {
              fixedOn: api.frameName,
              rect: { x: 0, y: 0, w: w, h: h },
              fixed: true,
              type: 2, //0拍照录像 1 录像 2 拍照
            },
            function (ret1) {
              var code1 = ret1.code;
              if (code1 == 0) {
                //关闭事件
              } else if (code1 == 2) {
                //返回图片路径path
                that.imageFilter(ret1.path);
              } else if (code1 == -1) {
                //错误信息
                alert(ret1.text);
              }
            }
          );
        }
      });
    },
    iosCamera() {
      let that = this;
      let zySmallVideo = api.require("zySmallVideo");
      zySmallVideo.openNew(
        {
          rect: {
            //模块 附于一个frame之上
            x: 0,
            y: 0,
            w: api.frameWidth,
            h: api.frameHeight,
          },
          fixedOn: api.frameName,
          fixed: true,
          videoInfo: {
            setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
            setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
            setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
          },
          MaxRecordTime: 60, //最大录制时间 单位秒 默认10
          MinRecordTime: 5, //最短录制时间  单位s
          MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
          setFeatures: 1001, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
          setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
          setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
          setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
          setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
          setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
          cameraInfo: {
            //摄像头 设置样式
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            margin_l: 0, //距左 默认都是0
            margin_r: 35, //距右
            margin_t: 65, //距上
            margin_b: 0, //距下
          },
          foucsInfo: {
            //点击的对焦框 样式
            color: "#cd0000", //线条颜色 默认16AE16
            width: 4, //线条宽度 默认4
          },
          recordInfo: {
            progress_color: "#cd0000", //进度条颜色 默认16AE16
            outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
            inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
          },
          confirmInfo: {
            //确认框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
          cancelInfo: {
            //取消框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.type == "captureSuccess") {
              that.imageFilter(ret.result);
            }
          }
        }
      );
    },

    //图片压缩
    imageFilter(imgPath) {
      let that = this;
      var imageFilter = api.require("imageFilter");
      var imageCachePath = api.cacheDir; //cache://协议对应的真实目录，字符串类型
      imageFilter.compress(
        {
          img: imgPath,
          quality: 0.5,
          size: "800X600",
          save: {
            album: false,
            imgPath: imageCachePath + "/",
            imgName: "cs.jpg",
          },
        },
        function (ret, err) {
          let imgUrl = imageCachePath + "/cs.jpg";
          that.getFileName("pic", imgUrl);
          //文件删除
          var fs = api.require("fs");
          fs.remove(
            {
              path: imgPath,
            },
            function (ret, err) {
              if (ret.status) {
              } else {
              }
            }
          );
        }
      );
    },

    recordAudio() {
      if (this.btnLoading) {
        Toast("正在播放...");
        return;
      }
      this.$ac.showProgress({
        title: "录制中...",
        text: "释放手指结束录音...",
        modal: false,
      });
      //开始录音
      this.$ac.startRecord({
        // path: 'fs://audio.amr',
        path: "fs://audio.aac",
        format: "aac",
      });
    },
    stopRecordAudio() {
      if (this.btnLoading) {
        return;
      }
      let that = this;
      that.$ac.hideProgress();
      that.$ac.stopRecord(function (ret, err) {
        if (ret) {
          that.getFileName("audio2", ret.path);
        }
      });
    },

    //获取文件名称
    async getFileName(fType, fUrl) {
      let type = "jpg";
      if (fType === "audio") {
        type = "amr";
      } else if (fType === "video") {
        type = "mp4";
      } else if (fType === "pic") {
        type = "jpg";
      } else if (fType === "audio2") {
        type = "aac";
      }
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/getFileName?fileType=" + type
      );
      if (res.code === 200) {
        //上传文件
        this.putObj(fType, fUrl, res.fileName);
      }
    },

    //定时器
    timeCycle(fType, fileName) {
      let that = this;
      let cycleNum = 0;
      that.uploadSuccess = false;
      let intervald = setInterval(() => {
        if (
          that &&
          !that._isDestroyed &&
          cycleNum < _httpClient.getUploadCycle() &&
          !that.uploadSuccess
        ) {
          setTimeout(() => {
            if (that && !that._isDestroyed) {
              that.queryFileUpload(fType, fileName);
              cycleNum++;
            }
          }, 0);
        } else {
          //清除定时器
          clearInterval(intervald);
          that.uploadSuccess = true;
          Toast.clear();
          if (cycleNum == _httpClient.getUploadCycle()) {
            alert("上传超时，请重试");
          }
        }
      }, 2000);
    },

    //查询文件是否上传成功
    async queryFileUpload(fType, fileName) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "校验保存中...",
      });
      let that = this;
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/" + fileName
      );
      if (res.code === 200) {
        let urls = res.objectURL.split("?");
        if (urls.length > 0) {
          if (fType === "audio") {
            that.equipRepairVo.audioList.push(urls[0]);
          } else if (fType === "video") {
            that.equipRepairVo.videoList.push(urls[0]);
          } else if (fType === "pic") {
            that.equipRepairVo.picList.push(urls[0]);
          } else if (fType === "audio2") {
            that.equipRepairVo.audioList.push(urls[0]);
          }
          Toast("上传成功");
        }
        Toast.clear();
        that.uploadSuccess = true;
      }
    },

    //文件上传
    putObj(fType, fUrl, fileName) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "上传中...0%",
      });
      api.ajax(
        {
          url:
            _httpClient.getApiPrefix() +
            "/minio/oss/appPutObject?fileName=" +
            fileName,
          //  url: 'http://192.168.2.102:8083' + '/minio/oss/putObject',
          method: "post",
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          report: true,
          data: {
            files: {
              file: fUrl,
            },
          },
        },
        function (ret, err) {
          if (ret) {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 0,
              message: "上传进度...\n" + ret.progress + "%",
            });
            if (ret.body.code === 200) {
              if (api.systemType == "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            } else if (ret.progress == 100) {
              if (api.systemType != "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            }
          } else {
            Toast.clear();
          }
        }
      );
    },

    // async putObj(fType, fUrl) {
    //   let _this = this
    //   Toast.loading({
    //     mask: true,
    //     forbidClick: true,
    //     duration: 0,
    //     message: '请稍等...',
    //   })
    //   try {
    //     let res = await _httpClient.postFile(_httpClient.getApiPrefix() + '/minio/oss/putObject', {
    //       files: {
    //         file: fUrl,
    //       },
    //     })
    //     if (res.code === 200) {
    //       if (res.fileUrl) {
    //         Toast.clear()
    //         if (fType === 'audio') {
    //           _this.equipRepairVo.audioList.push(res.fileUrl)
    //         } else if (fType === 'video') {
    //           _this.equipRepairVo.videoList.push(res.fileUrl)
    //         } else if (fType === 'pic') {
    //           _this.equipRepairVo.picList.push(res.fileUrl)
    //         }
    //       }
    //     }
    //   } catch (e) {
    //     Toast.fail(JSON.stringify(e))
    //   }
    // },
    showAudio(audioUrl) {
      //判断是播放还是暂停
      if (!this.btnLoading) {
        this.btnLoading = true;
        // this.audioStop = false
        if (audioUrl == "") {
          Dialog.alert({
            message: "当前无语音信息",
            theme: "round-button",
          }).then(() => {
            // on close
          });
        }
        var audioStreamer = api.require("audioStreamer");
        let _this = this;
        audioStreamer.addEventListener({}, function (ret) {
          if (ret.state == "finished") {
            _this.btnLoading = false;
            // _this.audioStop = true
          }
        });
        if (api.systemType == "ios") {
          api.download(
            {
              url: audioUrl,
            },
            function (res) {
              if (res.state == 1) {
                api.startPlay(
                  {
                    path: res.savePath,
                  },
                  function (ret, err) {
                    if (ret) {
                      // _that.activeAudio = ''
                    } else {
                      alert(JSON.stringify(err));
                    }
                  }
                );
              }
            }
          );
        } else {
          audioStreamer.openPlayer(
            {
              path: audioUrl,
            },
            function (ret) {}
          );
        }
      } else {
        var audioStreamer = api.require("audioStreamer");
        audioStreamer.pause();
        this.btnLoading = false;
        // this.audioStop = true
      }
    },
    // 取消
    concel() {
      if (this.operationType == 1) {
        api.sendEvent({
          name: "result",
          extra: {
            res: "next",
          },
        });
      }
      api.closeWin();
    },
    // 提交信息
    async doCheck() {
      let that = this;
      that.commitLoading = true;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "正在保存...",
      });
      let res = await _httpClient.post(
        _httpClient.getApiPrefix() + "/equip/repair/saveReportRepairInfo",
        {
          body: that.equipRepairVo,
        }
      );
      Toast.clear();
      if (res.code === 200) {
        that.commitLoading = false;
        Toast(res.msg);
        that.$ac.closeWin();
      }
    },
    startVideoRecord() {
      if (api.systemType == "ios") {
        let that = this;
        let zySmallVideo = api.require("zySmallVideo");
        zySmallVideo.openNew(
          {
            rect: {
              //模块 附于一个frame之上
              x: 0,
              y: 0,
              w: api.frameWidth,
              h: api.frameHeight,
            },
            fixedOn: api.frameName,
            fixed: true,
            videoInfo: {
              //视频高级设置 不懂请勿修改
              //videoSize_w:720,//视频分辨率 宽 默认720
              //videoSize_h:1280,//视频分辨率 高 默认1280
              setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
              setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
              setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
            },
            MaxRecordTime: 60, //最大录制时间 单位秒 默认10
            MinRecordTime: 5, //最短录制时间  单位s
            MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
            setFeatures: 1002, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
            setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
            setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
            setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
            setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
            setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
            cameraInfo: {
              //摄像头 设置样式
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              //w:120,// 摄像头宽度 默认 120
              //h:92,// 摄像头高度 默认 92
              margin_l: 0, //距左 默认都是0
              margin_r: 35, //距右
              margin_t: 65, //距上
              margin_b: 0, //距下
            },
            foucsInfo: {
              //点击的对焦框 样式
              color: "#cd0000", //线条颜色 默认16AE16
              width: 4, //线条宽度 默认4
            },
            recordInfo: {
              //录制时的参数
              //button_radius:120,//外圆半径 默认120
              //button_inside_radius:90,//内圆半径 默认90
              progress_color: "#cd0000", //进度条颜色 默认16AE16
              outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
              inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
              //strokeWidth:15,//进度条宽度 默认15
              //outside_add_size:48,//长按外圆半径变大的Size 默认48
              //inside_reduce_size:30,//长按内圆缩小的Size 默认30
            },
            confirmInfo: {
              //确认框参数
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              img: "", //设置自定义图片
              //w:220,//宽 默认200
              //h:220,//高 默认200
              //margin_r:170, //确认按距右
            },
            cancelInfo: {
              //取消框参数
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              img: "", //设置自定义图片
              //w:220,//宽 默认200
              //h:220,//高 默认200
              //margin_l:170,//确认按距左
            },
          },
          function (ret, err) {
            if (ret.status) {
              // fileUrl = ret.fileUrl
              // document.getElementById('videoPic').src = ret.result
              if (ret.type == "recordSuccess") {
                that.getFileName("video", ret.url);
              }
            }
          }
        );
      } else {
        let _this = this;

        let that = this;
        let zySmallVideo = that.$ac.require("zySmallVideo");
        zySmallVideo.open(
          {
            MaxRecordTime: 60,
            MinRecordTime: 6, //最短录制时间  单位s
            MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
            videoColor: api.systemType == "ios" ? 0xcd0000 : "#cd0000",
            AVAssetExportPreset: "AVAssetExportPreset1280x720",
            mVideoSizeW: 720,
            mVideoSizeH: 1280,
          },
          function (ret, err) {
            if (ret.result == "success") {
              that.getFileName("video", ret.fileUrl);
            }
          }
        );
      }
    },
    showVideo(videoUrl) {
      let that = this;
      if (!videoUrl) {
        Toast("请先录制视频");
        return;
      }
      that.$ac.openVideo({
        url: videoUrl,
      });
    },
    zySmallVideoGetThumbnail() {
      let that = this;
      let zySmallVideo = that.$ac.require("zySmallVideo");
      if (!that.equip.videoUrl) {
        Toast("请先录制视频");
        return;
      }
      zySmallVideo.getThumbnail(
        {
          fileUrl: that.equip.videoUrl,
        },
        function (ret, err) {
          alert(JSON.stringify(ret));
          // document.getElementById('videoPic').src = ret.filePic;
        }
      );
    },
    async delObj(fType, fUrl) {
      this.commitLoading = false;
      let fname = "";
      try {
        if (fUrl != undefined && fUrl != "" && fUrl != null) {
          fname = fUrl.substring(fUrl.lastIndexOf("/") + 1);
        }
        let res = await _httpClient.delete(
          _httpClient.getApiPrefix() + "/minio/oss/" + fname
        );
        if (res.code === 200) {
          let flist = [];
          if (fType === "audio") {
            flist = this.equipRepairVo.audioList;
          } else if (fType === "video") {
            flist = this.equipRepairVo.videoList;
          } else if (fType === "pic") {
            flist = this.equipRepairVo.picList;
          }
          if (flist.length > 0) {
            for (var i = 0; i < flist.length; i++) {
              if (flist[i] == fUrl) {
                flist.splice(i, 1);
              }
            }
          }
          Toast.success(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    // 获取当前时间
    getNowTime() {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      return dateTime;
    },
  },
};
</script>
<style>
html,
body {
  font-family: "Open Sans", sans-serif;
  background-color: White;
}

.mg5 {
  margin-right: 5px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 100%;
  width: 100%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.3);
}

.buttonright {
  position: fixed;
  right: 5px;
  bottom: 24px;
  width: 50%;
  height: 40px;
  font-size: 12px;
}

.buttonleft {
  position: fixed;
  left: 5px;
  bottom: 24px;
  width: 50%;
  height: 40px;
  font-size: 12px;
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 5rem;
  bottom: 5px;
  overflow: scroll;
  right: 0;
  width: 100%;
  margin-bottom: 4.7rem;
  z-index: 1;
}

.divStyle {
  /* border: 1px solid #dcdcdc; */
  border-top-width: 3px;
  border-left-width: 3px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 4px;
}

.confirmReport {
  position: fixed;
  right: 5px;
  bottom: 24px;
  width: 48%;
  height: 40px;
  font-size: 12px;
}

.concelReport {
  position: fixed;
  left: 5px;
  bottom: 24px;
  width: 48%;
  height: 40px;
  font-size: 12px;
}
</style>
